package com.yfbao.horizon.inspection.prometheus;

import org.springframework.stereotype.Component;

@Component
public class PromQLBuilder {

    /**
     * 构建堆内存使用率检查的复杂PromQL
     * 原查询：count_over_time((avg_over_time(((jvm_memory_used_bytes{area="heap",env='dev'}/jvm_memory_max_bytes{area="heap",env='dev'})*100>40)[5m:1m])>0.4)[1d:5m])>20
     */
    public String buildHeapMemoryUsageQuery(String env, Double usageThreshold,
                                            Double avgThreshold, Integer countThreshold) {

        // 设置默认值
        if (env == null) env = ".*"; // 匹配所有环境
        if (usageThreshold == null) usageThreshold = 40.0;
        if (avgThreshold == null) avgThreshold = 0.4;
        if (countThreshold == null) countThreshold = 20;

        return String.format(
                "count_over_time(" +
                        "(" +
                        "avg_over_time(" +
                        "(" +
                        "((jvm_memory_used_bytes{area=\"heap\",env=~\"%s\"} / " +
                        "jvm_memory_max_bytes{area=\"heap\",env=~\"%s\"}) * 100 > %f)" +
                        ")[5m:1m]" +
                        ") > %f" +
                        ")[1d:5m]" +
                        ") > %d",
                env, env, usageThreshold, avgThreshold, countThreshold
        );
    }

    /**
     * 构建动态环境参数的查询
     */
    public String buildQueryWithDynamicEnv(String baseQuery, String env) {
        if (env == null || env.trim().isEmpty()) {
            // 如果env为空，移除env过滤条件
            return baseQuery.replaceAll("\\{.*?env=~.*?\\}", "{}");
        } else {
            // 使用正则匹配支持多环境
            return baseQuery.replaceAll("env=~\\\".*?\\\"", "env=~\"" + env + "\"");
        }
    }

    /**
     * 构建JVM Full GC检查查询
     */
    public String buildFullGcQuery(String env, Integer days, Integer threshold) {
        if (days == null) days = 1;
        if (threshold == null) threshold = 1;

        String baseQuery = "increase(jvm_gc_pause_seconds_count{action=\"end of major GC\",env=~\"%s\"}[%dd]) > %d";
        return String.format(baseQuery, env != null ? env : ".*", days, threshold);
    }

    /**
     * 构建CPU使用率查询
     */
    public String buildCpuUsageQuery(String env, Double threshold) {
        if (threshold == null) threshold = 80.0;

        return String.format(
                "100 - (avg by (instance) (irate(node_cpu_seconds_total{mode=\"idle\",env=~\"%s\"}[5m])) * 100) > %f",
                env != null ? env : ".*", threshold
        );
    }
}
